import axios from 'axios'
import Qs from 'qs'
/**
 * http请求类，集成拦截器处理
 * opt = {
 *  baseURL: string 基础地址
 * }
 *
 */

class Http {
  constructor (opts) {
    // 初始化对象
    const options = Object.assign({
      baseURL: '',
      timeout: 5000,
      requestHandle: 'Content-Type:application/x-www-form-urlencoded',
      responseHandle: null
    }, opts)

    // 自定义创建实例
    this.http = axios.create({
      baseURL: options.baseURL,
      timeout: options.timeout
    })

    // 添加在发送请求时拦截器
    this.http.interceptors.request.use(
      (config) => {
        let configs = config

        if (options.requestHandle) {
          configs = options.requestHandle(config)
        }
        return configs
      },
      error => error
    )

    // 添加响应拦截器
    this.http.interceptors.response.use(
      (response) => {
        let responses = response
        if (options.responseHandle) {
          responses = options.responseHandle(response)
        }
        return Http.parseResponse(responses)
      },
      (error) => {
        let response = error.response
        if (options.responseHandle) {
          response = options.responseHandle(response, error)
        }
        return Http.parseResponse(response, error)
      }
    )
  }

  /**
     * 解析URl
     * @param url <string> '/aaa/:id
     * @param routeParam = <object|map> {id: 123} 将使用此对象的属性值替换url中参数
     * @param queryParam = <object|map> {name: 'abc', attr: 'def'} url 后面的查询参数
     * @returns {string}
     */
  parseUrl (url, {
    routeParam,
    queryParam
  } = {
    routeParam: null,
    queryParam: null
  }) {
    let urls = url
    if (routeParam) {
      urls = url.replace(/:[^/]+/g, (match, key) => routeParam[key])
    }
    if (queryParam) {
      const queryStrings = []
      for (const i in queryParam) {
        queryStrings.push(`${i}=${queryParam[i]}`)
      }
      urls += `?${queryStrings.join('&')}`
    }

    return urls
  }

  /**
     * 添加请求状态
     * @param response axios response
     * @param error axios error
     * @returns {*}
     *
     */
  static parseResponse (response, error = null) {
    if (response) {
      return {
        status: response.status === 200 || response.status === 201,
        data: response.data
      }
    } else if (error) {
      return {
        status: false,
        data: {
          ret: -1,
          data: null,
          message: error.message
        }
      }
    }
  }

  /**
     * 基础请求方式
     * @param url <String> '/aa/:id'
     * @param param <object|map> {
     *      routeParam = {id: 123} 将使用此对象的属性替换url中参数
     *      queryParam = {name: 'abc', attr: 'def'} url 后面参数
     * }
     * 解析后 URL= '/aa/123?name=abc&attr=def'
     * @returns {Promise<*>}
     *
     */
  get (url, param = null, config = null) {
    let urls = url
    if (param) {
      urls = this.parseUrl(url, param)
    }

    return this.http.get(urls, config)
  }

  post (url, data = {}, param = null, config = null) {
    let urls = url
    if (param) {
      urls = this.parseUrl(url, param)
    }
    console.log(config)
    // 上传
    if (urls === '/h5/person/purposeUpload' || urls === '/h5/shopUser/purposeUpload') {
      // data = Qs.stringify(data)
    } else {
      data = Qs.stringify(data)
    }

    return this.http.post(urls, data, config)
  }

  put (url, data = null, param = null, config = null) {
    let urls = url
    if (param) {
      urls = this.parseUrl(url, param)
    }
    return this.http.put(urls, data, config)
  }

  patch (url, data = null, param = null, config = null) {
    let urls = url
    if (param) {
      urls = this.parseUrl(urls, param)
    }
    return this.http.patch(urls, data, config)
  }

  delete (url, param = null, config = null) {
    let urls = url
    if (param) {
      urls = this.parseUrl(urls, param)
    }
    return this.http.delete(urls, config)
  }
}

export { Http }
